#encoding:utf-8

from flask import (abort, Blueprint, current_app, flash, redirect,
                   render_template, request, url_for)
from flask.ext.login import login_required, login_user, logout_user

from app.ext import mongo
from app.models import Account

app = Blueprint('passport', __name__)

@app.route('/login', methods=['POST', 'GET'])
def login():

    # check account and init
    uid = current_app.config['UID']
    pwd = current_app.config['PWD']
    user = mongo.db.account.find_one({'login_id': uid})
    if not user:
        mongo.db.account.insert({'login_id':uid, 'password': pwd})
    else:
        user['password']=pwd
        mongo.db.account.save(user)


    if request.method == 'GET':
        return render_template('login.html')
    else:
        uid = request.form.get('login_id')
        password = request.form.get('password')
        user = mongo.db.account.find_one({'login_id': uid, 'password': password})
        ac = Account(_id=user['_id'], login_id=user['login_id'], password=user['password'])
        if user:
            login_user(ac)
            return redirect(url_for('backend.players'))
        else:
            flash(u'帐号或密码错误！')
            return render_template('login.html')
@app.route('/logout', methods=['GET', 'POST'])
def logout():
    logout_user()
    return redirect('')

